// 内容区组件

import { computed, defineComponent, inject, onMounted, reactive, ref } from "vue";
import { BlockResizer } from "./block-resizer";
import axios from "axios";
import { events } from "./events";

export default defineComponent({
  props: {
    block: { type: Object },
    formData: { type: Object },
    customProps: { type: Object },
  },
  setup(props) {
    const blockStyles = computed(() => ({
      top: `${props.block.top}px`,
      left: `${props.block.left}px`,
      zIndex: `${props.block.zIndex}`,
    }));

    const config = inject("config");
    const blockRef = ref(null);

    // 给每个加载的block设置高度宽度
    onMounted(() => {
      let { offsetWidth, offsetHeight } = blockRef.value;
      console.log(props.block);
      if (props.block.alignCenter) {
        // 拖拽放手时渲染
        props.block.left = props.block.left - offsetWidth / 2;
        props.block.top = props.block.top - offsetHeight / 2;
        props.block.alignCenter = false;
      }
      //渲染完成后添加高宽
      props.block.width = offsetWidth;
      props.block.height = offsetHeight;

      // 加载异步数据
      if (props.block?.request) {
        getViewParam(props.block?.url);
        // 绑定刷新事件
        events.on("refresh", () => {
          if (props.block?.url) {
            getViewParam(props.block?.url);
          }
        });
      }
    });

    // 获取通用接口的视图数据，包括属兔中展示的字段名，数据行
    let result = reactive({ options: [], data: [] });

    const getViewParam = async (url) => {
      let arg = {
        id: 32, // 人员视图id
        pageIndex: 1,
        pageSize: 15,
        conditions: [],
      };

      let d = await axios.post(url, arg);
      let list = d.data.data.list;
      let viewParam = d.data.data.viewParam;
      let template = viewParam.templateContainerList[0];
      let fieldList = template.fieldList;
      // 提取字段名名{label: title, value: viewPropNmae}, 如果viewPropName中有.，则取前部分
      let options = fieldList.map((m) => {
        return {
          label: m.title,
          value: m.viewPropertyName.includes(".")
            ? m.viewPropertyName.substring(0, m.viewPropertyName.indexOf("."))
            : m.viewPropertyName,
        };
      });
      result.options = options;
      result.data = list;
    };

    return () => {
      // 通过block的key属性直接获取对应的组件
      const component = config.componentMap[props.block.key];
      // 获取组件的拉伸方式
      const { width: isResizeWidth, height: isResizeHeight } = component?.resize || {};
      // 获取组件的渲染函数
      const renderProps = {
        size: props.block?.hasResize
          ? {
              // 调整大小
              width: props.block.width,
              height: props.block.height,
            }
          : {},
        globalActions: props.block.props?.globalActions,
        localActions: props.block.props?.localActions,
        height: props.block?.width,
        width: props.block?.height,
        // 如果有异步请求，则返回数据
        props: props.block?.request ? result : props.block?.props || {}, // 属性默认的props
        // 表单模型
        model: Object.keys(component.model || {}).reduce((prev, propName) => {
          const modelName = !props.block?.model ? null : props.block.model[propName];
          prev[propName] = {
            [propName === "default" ? "modelValue" : propName]: props.formData[modelName],
            [propName === "default" ? "onUpdate:modelValue" : "onChange"]: (val) => (props.formData[modelName] = val),
          };
          return prev;
        }, {}),
        // 自定义属性，如事件
        custom: !props.block?.slotName || !props.customProps ? {} : props.customProps[props.block?.slotName] || {},
      };

      const rednerComponent = component.render(renderProps);

      return (
        <div class="editor-block" style={blockStyles.value} ref={blockRef}>
          {rednerComponent}
          {/* 判断是否添加拉伸 */}
          {props.block?.focus && (isResizeWidth || isResizeHeight) && (
            <BlockResizer block={props.block} component={component}></BlockResizer>
          )}
        </div>
      );

      // return <div class="editor-block" style={blockStyles.value}>组件显示区</div>
    };
  },
});
